import {
  Attachments,
  Bubble,
  Conversations,
  Prompts,
  Sender,
  Welcome,
  useXAgent,
  useXChat,
} from '@ant-design/x';
import React, { useEffect, useRef, useState } from 'react';
import {
  CloudUploadOutlined,
  CommentOutlined,
  EllipsisOutlined,
  FireOutlined,
  HeartOutlined,
  PaperClipOutlined,
  PlusOutlined,
  ReadOutlined,
  ShareAltOutlined,
  SmileOutlined,
  LoadingOutlined,
  UserOutlined,
  CopyOutlined,
  FrownOutlined,
  ReloadOutlined,
  OpenAIOutlined
} from '@ant-design/icons';
import { Badge, Button, Space, message, Flex } from 'antd';
import { BASE_URL, PATH, MODEL, API_KEY } from '@/core/modalSetting';
import ChatMarkdown from './components/ChatMarkdown';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import {fileToBase64, useStyle, defaultConversationsItems, placeholderPromptsItems, senderPromptsItems, 
  roles, welcomeProps
} from './chatMethods';
import SettingForm, { defaultModelParams } from './components/SettingForm';
import {omit} from 'lodash-es';
import themeConfig from '@/core/themeConfig';

const Chat = () => {
  const { styles } = useStyle();
  const [headerOpen, setHeaderOpen] = useState(false);
  const [content, setContent] = useState('');
  const [conversationsItems, setConversationsItems] = useState(defaultConversationsItems);
  const [activeKey, setActiveKey] = useState(defaultConversationsItems[0].key);
  const [attachedFiles, setAttachedFiles] = useState([]);
  const [error, setError] = useState(null);
  const [isStreaming, setIsStreaming] = useState(false);
  const [modelParams, setModelParams] = useState(defaultModelParams);
  const responseIdRef = useRef(null);
  const attachmentsRef = React.useRef(null);
  const senderRef = React.useRef(null);
  // 修改：新增两个 ref 用于跟踪思考状态，模仿 Python 中的 thinking_state 和 currentThinkContent
  const thinkingStateRef = useRef({ thinking: -1 });
  const currentThinkContentRef = useRef('');

  // 添加新的 state 来存储所有对话内容
  const [conversationsData, setConversationsData] = useState(() => {
    // 从 localStorage 获取已存储的对话
    const saved = localStorage.getItem('conversations');
    return saved
      ? JSON.parse(saved)
      : {
          '0': [
            {
              role: 'system',
              content: defaultModelParams.system_prompt,
              id: 'system-init',
            },
          ],
        };
  });

  // 保存对话到 localStorage
  useEffect(() => {
    localStorage.setItem('conversations', JSON.stringify(conversationsData));
  }, [conversationsData]);

  // 修改：改造后的解析器，参考 Python 代码处理请求数据的逻辑，增加对 reasoning_content 的处理以及思考状态转换
  const parser = (chunk) => {
    if (chunk.data.trim() === '[DONE]') {
      return { content: '', role: 'assistant' };
    }
    try {
      const data = JSON.parse(chunk.data);
      let content = data.choices[0].delta?.content || '';
      const role = data.choices[0].delta?.role || 'assistant';
      // 修改：新增对 reasoning_content 的处理，与 Python 中保持一致
      const reasoningContent = data.choices[0].delta?.reasoning_content || '';

      // 状态机处理 thinking 标签
      let stateOutput = '';

      // 修改：状态转换：未开始 -> 思考中
      if (thinkingStateRef.current.thinking === -1 && reasoningContent) {
        thinkingStateRef.current.thinking = 0;
        stateOutput = '<think>\n';
        currentThinkContentRef.current = '';
      }
      // 修改：状态转换：思考中 -> 已回答
      else if (thinkingStateRef.current.thinking === 0 && !reasoningContent && content) {
        thinkingStateRef.current.thinking = 1;
        stateOutput = '\n</think>\n\n';
      }

      // 处理实际内容，优先显示 reasoning_content
      let processedContent = reasoningContent || content;

      // 如果有状态输出，先返回状态标记，再返回实际内容
      if (stateOutput) {
        return { content: stateOutput + processedContent, role };
      }

      // 修改：特殊处理 <think> 和 </think> 标签，将其转换为 HTML 元素（div），以保证前端显示效果
      if (processedContent.includes('<think>')) {
        // processedContent = processedContent.replace('<think>', '<div className="think-content">');
      }
      if (processedContent.includes('</think>')) {
        // const thinkContent = processedContent.match(/<div className="think-content">(.*?)<\/think>/s);
        // if (thinkContent && thinkContent[1].trim()) {
        //   processedContent = processedContent.replace('</think>', '</div>');
        // } else {
        //   processedContent = processedContent.replace('<div className="think-content">', '');
        // }
      }

      return { content: processedContent, role };
    } catch (e) {
      console.error('解析错误:', e);
      return { content: '', role: 'assistant' };
    }
  };

  // ==================== Runtime ====================
  const [agent] = useXAgent({
    baseURL: BASE_URL + PATH,
    model: modelParams.model,
    dangerouslyApiKey: API_KEY,
  });

  const { messages, setMessages } = useXChat({
    agent,
    initialMessages: [
      {
        role: 'system',
        content: defaultModelParams.system_prompt,
        id: 'system-init',
      },
    ],
  });

  // 当 messages 改变时，更新 conversationsData
  useEffect(() => {
    if (activeKey !== undefined) {
      setConversationsData((prev) => ({
        ...prev,
        [activeKey]: messages,
      }));
    }
  }, [messages, activeKey]);

  // ==================== Event ====================
  const onSubmit = async (nextContent) => {
    if (!nextContent) return;
    setError(null);

    // 修改：重置思考状态，参考 Python 中的 thinking_state 初始化
    thinkingStateRef.current = { thinking: -1 };
    currentThinkContentRef.current = '';
    console.log(nextContent, attachedFiles);
    let newContent

    newContent = nextContent

    const userMessage = {
      role: 'user',
      content: newContent,
      id: `user_${Date.now()}`,
    };

    // 添加用户消息到消息列表
    setMessages((prevMessages) => [...prevMessages, userMessage]);
    setContent('');
    setAttachedFiles([]);

    // 创建一个空的响应消息以显示加载状态
    const responseId = `assistant_${Date.now()}`;
    responseIdRef.current = responseId;

    setMessages((prevMessages) => [
      ...prevMessages,
      {
        role: 'assistant',
        content: '',
        id: responseId,
      },
    ]);

    setIsStreaming(true);

    try {
      // 修改：处理消息以防止连续的相同角色，参照 Python 中的消息处理逻辑
      let processedMessages = [...messages, userMessage];
      
      // 添加：确保系统预置消息存在
      if (!processedMessages.some(msg => msg.role === 'system')) {
        processedMessages.unshift({
          role: 'system',
          content: modelParams.system_prompt || defaultModelParams.system_prompt,
          id: `system_${Date.now()}`,
        });
      }

      let i = 0;
      while (i < processedMessages.length - 1) {
        if (processedMessages[i].role === processedMessages[i + 1].role) {
          const alternateRole = processedMessages[i].role === 'user' ? 'assistant' : 'user';
          processedMessages.splice(i + 1, 0, {
            role: alternateRole,
            content: '[Unfinished thinking]',
            id: `placeholder_${Date.now()}_${i}`,
          });
        }
        i += 1;
      }

      await agent.request(
        {
          messages: processedMessages,
          stream: true,
          ...omit(modelParams, ['system_prompt']),
        },
        {
          onUpdate: (message) => {
            const parsedMessage = parser(message);
            if (parsedMessage.content) {
              // 更新现有消息而不是创建新消息
              setMessages((prevMessages) => {
                return prevMessages.map((msg) => {
                  if (msg.id === responseIdRef.current) {
                    return {
                      ...msg,
                      content: msg.content + parsedMessage.content,
                    };
                  }
                  return msg;
                });
              });
            }
          },
          onSuccess: () => {
            setIsStreaming(false);
            // 修改：请求完成后重置思考状态，保持和 Python 逻辑一致
            thinkingStateRef.current = { thinking: -1 };
          },
          onError: (err) => {
            setIsStreaming(false);
            setError(err);
            console.error('API请求失败:', err);
            // 修改：请求出错时重置思考状态
            thinkingStateRef.current = { thinking: -1 };
          },
        }
      );
    } catch (err) {
      setIsStreaming(false);
      setError(err);
      console.error('API请求失败:', err);
      thinkingStateRef.current = { thinking: -1 };
    }
  };

  const onPromptsItemClick = (info) => {
    onSubmit(info.data.description);
  };

  // 修改：切换对话时加载对应消息
  const onConversationClick = (key) => {
    setActiveKey(key);
    const conversationMessages =
      conversationsData[key] || [
        {
          role: 'system',
          content: defaultModelParams.system_prompt,
          id: 'system-init',
        },
      ];
    setMessages(conversationMessages);
  };

  // 修改：添加新对话时初始化对话内容
  const onAddConversation = () => {
    const newKey = `${conversationsItems.length}`;
    setConversationsItems([
      ...conversationsItems,
      {
        key: newKey,
        label: `New Conversation ${conversationsItems.length}`,
      },
    ]);
    setConversationsData((prev) => ({
      ...prev,
      [newKey]: [
        {
          role: 'system',
          content: defaultModelParams.system_prompt,
          id: 'system-init',
        },
      ],
    }));
    setActiveKey(newKey);
  };

  const handleFileChange = (info) => setAttachedFiles(info.fileList);

  // ==================== Nodes ====================
  const placeholderNode = (
    <Space direction="vertical" size={16} className={styles.placeholder}>
      <Welcome {...welcomeProps} />
      <Prompts
        title="你可以试着问我"
        items={placeholderPromptsItems}
        styles={{
          list: {
            width: '100%',
          },
          item: {
            flex: 1,
          },
        }}
        onItemClick={onPromptsItemClick}
      />
    </Space>
  );

  const getCopyContent = (content) => {
    const regex = /<think>\s*\n(.*?)\n\s*<\/think>(\n+)/s;
    return content.replace(regex, '');
  }

  // 消息渲染适配
  const items = messages
    .filter((msg) => msg.role !== 'system') // 过滤系统消息
    .map(({ id, content, role }) => {
      const formatContent = {
        key: id,
        role: role === 'user' ? 'local' : 'assistant', // 适配Ant Design X的展示角色
        loadingRender: () => (<div><LoadingOutlined /> 思考中...</div>),
        content: role === 'assistant' ? <ChatMarkdown value={content}></ChatMarkdown> : content,
        loading:
          role === 'assistant' && isStreaming && id === responseIdRef.current && content === '',
        }
      if(role === 'assistant' && (!isStreaming || id != responseIdRef.current)) {
        formatContent.footer = (
          <div>
            {/* <div className='text-small gray'>首token 2.59s | 搜索耗时 1.45s | 输出 41tokens/s | 总耗时 7s | 共调用 3554tokens</div> */}
            <div className='flex align-center'>
              <CopyToClipboard text={getCopyContent(content)} onCopy={() => message.success('复制成功！')}>
                  <Button size="small" type="text" icon={<CopyOutlined />} />
              </CopyToClipboard>
              {/* <Button onClick={refreshCurrent} size="small" type="text" icon={<ReloadOutlined />} /> */}
              {/* <Button size="small" type="text" icon={<SmileOutlined />} />
              <Button size="small" type="text" icon={<FrownOutlined />} /> */}
            </div>
          </div>
        )
      }
      return formatContent;
    })

  const attachmentsNode = (
    <Badge dot={attachedFiles.length > 0 && !headerOpen}>
      <Button type="text" icon={<PaperClipOutlined />} onClick={() => setHeaderOpen(!headerOpen)} />
    </Badge>
  );

  const senderHeader = (
    <Sender.Header
      title="Attachments"
      open={headerOpen}
      onOpenChange={setHeaderOpen}
      styles={{
        content: {
          padding: 0,
        },
      }}
    >
      {/* <Attachments
        maxCount={1}
        accept='image/*'
        ref={attachmentsRef}
        beforeUpload={() => false}
        items={attachedFiles}
        onChange={handleFileChange}
        placeholder={(type) =>
          type === 'drop'
            ? {
                title: 'Drop file here',
              }
            : {
                icon: <CloudUploadOutlined />,
                title: 'Upload files',
                description: 'Click or drag files to this area to upload',
              }
        }
        getDropContainer={() => senderRef.current?.nativeElement}
      /> */}
    </Sender.Header>
  );

  const logoNode = (
    <div className={styles.logo}>
      <img
        src={themeConfig.LOGO}
        draggable={false}
        alt="logo"
      />
    </div>
  );

  // 处理参数变化
  const handleParamsChange = (changedValues, allValues) => {
    setModelParams(allValues);
    // 如果修改了 system_prompt，更新当前对话的系统消息
    if ('system_prompt' in changedValues) {
      setMessages(messages => {
        const updatedMessages = [...messages];
        if (updatedMessages[0]?.role === 'system') {
          updatedMessages[0].content = changedValues.system_prompt;
        }
        return updatedMessages;
      });
    }
  };

  // ==================== Render =================
  return (
    <div className={styles.layout}>
      <div className={styles.menu}>
        {/* 🌟 Logo */}
        {logoNode}
         {/* 使用独立的设置表单组件 */}
         <div style={{ padding: '0 12px' }}>
          <SettingForm 
            onChange={handleParamsChange}
            initialValues={defaultModelParams}
          />
        </div>

        {/* 🌟 添加会话 */}
        {/* <Button
          onClick={onAddConversation}
          type="link"
          className={styles.addBtn}
          icon={<PlusOutlined />}
        >
          New Conversation
        </Button> */}
        {/* 🌟 会话管理 */}
        {/* <Conversations
          items={conversationsItems}
          className={styles.conversations}
          activeKey={activeKey}
          onActiveChange={onConversationClick}
        /> */}
      </div>
      <div className={styles.chat}>
        {/* 🌟 消息列表 */}
        <Bubble.List
          items={
            error
              ? [
                  {
                    role: 'assistant',
                    content: `错误: ${error.message}`,
                    variant: 'error',
                  },
                ]
              : items.length > 0
              ? items
              : [
                  {
                    content: placeholderNode,
                    variant: 'borderless',
                  },
                ]
          }
          roles={roles}
          className={styles.messages}
        />
        {/* 🌟 提示词 */}
        <Prompts items={senderPromptsItems} onItemClick={onPromptsItemClick} />
        {/* 🌟 输入框 */}
        <Sender
          ref={senderRef}
          value={content}
          header={senderHeader}
          onSubmit={onSubmit}
          onChange={setContent}
          // prefix={attachmentsNode}
          loading={isStreaming}
          className={styles.sender}
          // onPasteFile={(file) => {
          //   attachmentsRef.current?.upload(file);
          //   setOpen(true);
          // }}
        />
      </div>
    </div>
  );
};

export default Chat;
